package com.webtest.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.webtest.dao.BookMapper;
import com.webtest.dao.BorrowMapper;
import com.webtest.dao.CommentMapper;
import com.webtest.dao.admin.AdminBookMapper;
import com.webtest.entity.Book;
import com.webtest.entity.Borrow;
import com.webtest.entity.Comment;
import com.webtest.entity.User;
import com.webtest.service.BorrowService;
import com.webtest.service.ReturnService;
import com.webtest.service.UserService;
import com.webtest.service.admin.AdminUserService;
import com.webtest.vo.SearchBooks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class AdminBookBorrowController {
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private BorrowService borrowService;
    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private AdminBookMapper adminBookMapper;
    @Autowired
    private ReturnService returnService;

    @Autowired
    private UserService userService;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private BookMapper bookMapper;

    @RequestMapping("/borrow")
    public String toMyBorrow(HttpSession session, Model model,@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum){
        //根据用户id查所有其所有借阅信息
       SearchBooks searchBooks= new SearchBooks();
       searchBooks.setName("");
        PageInfo<Book> booklist = borrowService.findBookList(pageNum,6,searchBooks);
        model.addAttribute("pageInfo",booklist);
        return "admin/borrow";
    }

    //搜索
    @PostMapping("/borrow/search")
    public String searchBooks(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                              Model model, SearchBooks searchBooks){
//        书名或书号条件搜索
        PageInfo<Book> booklist = borrowService.findBookList(pageNum,10,searchBooks);
        model.addAttribute("pageInfo",booklist);
        return "admin/borrow::bookList";
    }

//    @GetMapping("/borrow/{bookId}/return")
//    @Transactional
//    public String borrowBook(@PathVariable Integer bookId, RedirectAttributes attributes, HttpSession session) {
//        User user = (User) session.getAttribute("user");
//        System.out.println(bookId);
//        Integer stuId = user.getStuid();
//        //根据用户id查所有其所有借阅信息
//        List<Book> bookByBorrow = borrowService.findBookByBorrow(stuId);
//        //删除借阅信息
//        returnService.deleteBorrow(bookId,stuId);
//        returnService.updateReturnBook(bookId);
//        attributes.addFlashAttribute("message", "恭喜您，还书成功");
//        return "redirect:/admin/borrow";
//    }


    @RequestMapping("/borrow/total")
    @Transactional
    public String total(HttpSession session, Model model){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        SearchBooks searchBooks = new SearchBooks();
        searchBooks.setName("");
        //获取3月时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH,3);
        searchBooks.setEndTime(dateFormat.format(calendar.getTime()));

        List<Book> books = borrowMapper.searchBorrowBookByIdOrName(searchBooks);
        List<User> allUser = adminUserService.findAllUser();
        Map<Integer,User> userMap = new HashMap<>();
        for(User user : allUser){
            userMap.put(user.getId(),user);
        }

        Map<Integer,Integer> zuNum = new HashMap<>();
        List<Borrow> result = new ArrayList<>();
        for(Book book : books){
            book.getBorrow().setDamages(Borrow.calc(book.getBorrow(),book,userMap.get(book.getBorrow().getStuId())));;
            result.add(book.getBorrow());
            if(zuNum.get(book.getId()) == null){
                zuNum.put(book.getId(),1);
            }else{
                zuNum.put(book.getId(),zuNum.get(book.getId()));
            }
        }
        for(Borrow borrow : result){
           borrowMapper.updateBrrowMoney(borrow);
        }
        adminBookMapper.updateAllBookStatus2();
        for(Map.Entry<Integer,Integer> one :zuNum.entrySet()){
            Book book = new Book();
            book.setId(one.getKey());
            book.setStatus(one.getValue());
//            if(one.getValue() >=5){
//                book.setStatus(3);
//            }else if(one.getValue()>0){
//                book.setStatus(1);
//            }
            adminBookMapper.updateBookStatus(book);
        }

        //评分统计
        List<Comment> comments = commentMapper.selectAll();
        Map<Integer,List<Comment>> map = new HashMap<>();
        List<Book> booksGood = new ArrayList<>();
        for(Comment one :comments){
            if(map.get(one.getBookId())==null){
                map.put(one.getBookId(),new ArrayList<>());
            }
            map.get(one.getBookId()).add(one);
        }
        for(Map.Entry<Integer,List<Comment>> one : map.entrySet()){
            Book book = new Book();
            double count = 0;
            double size = 0;
            for(Comment comment : one.getValue()){
                count+= comment.getScore();
                size++;
            }
            book.setId(one.getKey());
            book.setGood(count / size);
            bookMapper.updateGoodById(book);
        }

        return "redirect:/admin/borrow";
    }
}
